package com.itheima.activiti.service.business.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.activiti.auth.JwtContextUtils;
import com.itheima.activiti.entity.business.Leaves;
import com.itheima.activiti.mapper.business.LeaveMapper;
import com.itheima.activiti.service.business.LeaveService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LeaveServiceImpl extends ServiceImpl<LeaveMapper, Leaves> implements LeaveService {

    private static final String PROCESS_KEY = "leave";

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Override
    public ProcessInstance start(Leaves leaves) {
        //保存请假单
        leaves.setName(JwtContextUtils.getUser().getName());
        this.save(leaves);

        //设置发起人Id
        String currentUserId = JwtContextUtils.getUser().getId().toString();
        Authentication.setAuthenticatedUserId(currentUserId);

        //启动流程实例
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(PROCESS_KEY, leaves.getId());

        //完成发起人任务
        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();
        taskService.setAssignee(task.getId(), currentUserId);
        taskService.addComment(task.getId(), null, leaves.getDescription());
        taskService.complete(task.getId());
        return instance;
    }

    @Override
    public ProcessInstance commit(Leaves leaves) {
        leaves = this.getById(leaves.getId());
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(leaves.getId()).singleResult();

        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();
        taskService.deleteComments(task.getId(), instance.getProcessInstanceId());
        taskService.addComment(task.getId(), instance.getProcessInstanceId(), leaves.getDescription());
        taskService.complete(task.getId());
        return instance;
    }
}
